<template>
    <view class="form">
        <view class="margin-md padding-md bg-white border-radius-md" v-for="(thing, tIndex) in thingOptions"
            :key="tIndex + '_thing'">
            <uv-divider :text="thing.title"></uv-divider>
            <view class="form-row">
                <view class="form-row_label">选择时间</view>
                <view classs="form-row_value">
                    <view class="tags" style="grid-template-columns: repeat(4, 1fr)">
                        <view v-for="(time, tKey) in timeOptions" :key="tKey">
                            <uv-tags size="mini" :text="time.text" :plain="formModelList[tIndex].start_at != time.value"
                                type="primary" :name="time.value" @click="selectTime(time, tIndex)"></uv-tags>
                        </view>
                    </view>
                </view>
            </view>
            <view class="form-row">
                <view class="form-row_label">输入数量</view>
                <view class="form-row_value">
                    <view class="num">
                        <view class="" style="width: 40%">
                            <uv-input type="number" v-model="formModelList[tIndex].num" maxlength="6"
                                placeholder="请输入数量">
                                <!-- vue3模式下必须使用v-slot:suffix -->
                                <template v-slot:suffix>
                                    {{ thing.unit }}
                                </template>
                            </uv-input>
                        </view>
                    </view>
                </view>
            </view>

            <view class="form-row">
                <view class="form-row_label">输入备注</view>
                <view class="form-row_value">
                    <uv-input v-model="formModelList[tIndex].remark" maxlength="60" placeholder="请输入备注"></uv-input>
                </view>
            </view>
        </view>

        <fixed-button :isLoading="submiting" @on-tap="submit"></fixed-button>
    </view>
</template>


<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
import type { ThingOption, FormModel } from './type';
import dayjs from '@/utils/dayjs';
import { createRecordBatch } from '@/api';
import useAppStore from '@/store/app';

const timeOptions = [
    { text: "现在", value: "0" },
    { text: "5分钟前", value: "5" },
    { text: "10分钟前", value: "10" },
    { text: "30分钟前", value: "30" },
    { text: "45分钟前", value: "45" },
    { text: "1小时前", value: "60" },
    { text: "2小时前", value: "120" },
    { text: "3小时前", value: "180" },
];
const appStore = useAppStore();


var thingOptions = ref<ThingOption[]>([])
var formModelList = ref<FormModel[]>([]);

onLoad((op: any) => {
    var _thingOptions = JSON.parse(op.rows);
    var _formModelList = _thingOptions.map((item: ThingOption) => {
        var __formRow: FormModel = {
            title: item.title,
            num: item.init_num ? (item.init_num as unknown as string) : '',
            unit: item.unit,
            start_at: '0',
            end_at: '',
            remark: ''
        };
        return __formRow;
    });

    thingOptions.value = _thingOptions;
    formModelList.value = _formModelList;
})

function selectTime(time: any, index: number) {
    formModelList.value[index].start_at = `${time.value}`;
}

var submiting = ref(false);

// 确认提示
function confirmTip(msg: string, showCancel: boolean = true) {
    return new Promise((reslove, reject) => {
        uni.showModal({
            title: '系统提示',
            content: msg,
            showCancel: showCancel,
            success: (res) => {
                reslove(res.confirm);
            },
            fail: () => {
                reject(false);
            }
        });
    });
}

async function submit() {
    // 脱离响应式防止后面改动数据影响界面
    var rows: FormModel[] = JSON.parse(JSON.stringify(formModelList.value));
    // 校验数据
    var validateRes = _isValidate(rows);
    if (!validateRes) return;

    // 询问确认提交
    var confirmResult = await confirmTip('你确定提交当前表单数据吗~');
    if (!confirmResult) return;
    try {
        submiting.value = true;
        // 处理开始时间
        rows.forEach((item: FormModel) => {
            item.start_at = dayjs().subtract(Number(item.start_at), 'minute').format('YYYY-MM-DD HH:mm:ss');
        });
        await createRecordBatch({ rows });
        submiting.value = false;
        const toPageTipRes = await confirmTip('数据已提交，跳转列表页~');
        if (toPageTipRes) {
            uni.redirectTo({
                url: '/pages/index/index',
                success: () => {
                    appStore.currentTab = 1;
                }
            });
        } else {
            uni.navigateBack();
        }

        submiting.value = false;
    } catch (error) {
        //TODO handle the exception
        submiting.value = false;
    }
}

const _isValidate = (rows: FormModel[]): boolean => {
    try {
        rows.forEach((item) => {
            if (!item.start_at) {
                throw new Error(`请选择${item.title}的时间`);
            }
            if (!item.num) {
                throw new Error(`请输入${item.title}的数量`);
            }
        });
        return true;
    } catch (error: any) {
        //TODO handle the exception
        confirmTip(error.message || '数据填写错误', false);
        return false;
    }
};

</script>

<style lang="scss" scoped>
.form {
    padding: 1rpx;

    &-row {
        margin-bottom: 50rpx;

        &_label {
            margin-bottom: 20rpx;
        }
    }

    .tags {
        display: grid;
        grid-gap: 30rpx;
        grid-template-columns: repeat(3, 1fr);

        ::v-deep(.uv-tags) {
            .uv-tags__text {
                width: 100%;
                text-align: center;
            }
        }
    }
}
</style>